import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { selectVideoEffectById, updateVideoProperties } from '@/store/videosSlice';
import { selectStickerById, updateStickerProperties } from '@/store/stickersSlice';
import type { RootState } from '@/store';
import { getAllVideoEffects } from '@/services/project';
import { Form, Select, Spin, Typography, Input, Button } from 'antd';
import { createGlobalStyle } from 'styled-components';

const { Title, Text } = Typography;
const { Option } = Select;

interface ConfigVideoEffectFormProps {
    videoId: string;
}

// 全局 Ant Design 深色主题样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* 自定义滚动条样式 */
    .config-video-effect-scroll::-webkit-scrollbar {
        width: 3px; background: transparent;
    }
    .config-video-effect-scroll::-webkit-scrollbar-thumb {
        background: #715BB8; border-radius: 4px;
    }
    /* 表单标签 */
    .ant-form-item-label > label {
        color: #FFFFFF !important;
    }
    /* 输入/选择控件 */
    .ant-input, .ant-input-number, .ant-select-selector {
        background-color: #3C3C3C !important;
        color: #FFFFFF !important;
        border-color: #555555 !important;
    }
    .ant-input:hover, .ant-input:focus,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important;
        box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-select-dropdown { background-color: #3C3C3C !important; }
    .ant-select-item-option { color: #FFFFFF !important; }
    .ant-select-item-option-selected { background-color: #555555 !important; }
    .ant-select-arrow { color: #FFFFFF !important; }
`;

const EFFECT_TYPE = 'Video_scene_effect_type';

const ConfigVideoEffectForm: React.FC<ConfigVideoEffectFormProps> = ({ videoId }) => {
    const [form] = Form.useForm();
    const dispatch = useDispatch();

    // 判断是否为贴纸
    const isSticker = videoId?.includes('sticker') || false;

    // 根据是否为贴纸选择不同的selector
    const mediaEffects = useSelector((state: RootState) => {
        if (!videoId) return [];
        if (isSticker) {
            const sticker = selectStickerById(state, videoId);
            return sticker?.effect || [];
        }
        return selectVideoEffectById(state, videoId);
    });

    const [effectsData, setEffectsData] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);

    const currentEffect = useMemo(() => {
        const effects = Array.isArray(mediaEffects) ? mediaEffects : [];
        return effects.find((effect) => effect.effect_type === EFFECT_TYPE) || null;
    }, [mediaEffects]);

    useEffect(() => {
        setLoading(true);
        getAllVideoEffects()
            .then((res) => {
                const sceneEffects = [...(res.data?.data?.free || []), ...(res.data?.data?.vip || [])];
                setEffectsData(sceneEffects);
            })
            .finally(() => setLoading(false));
    }, []);

    useEffect(() => {
        if (currentEffect) {
            form.setFieldsValue({ effect: currentEffect.params });
        } else {
            form.resetFields(['effect']);
        }
    }, [currentEffect, form]);

    // 专门处理特效选择变化的方法
    const handleEffectChange = useCallback(
        (effectValue: string) => {
            if (!videoId) return;

            const currentEffects = Array.isArray(mediaEffects) ? mediaEffects : [];
            let updatedEffects;

            if (effectValue) {
                // 添加或更新特效
                const effectIndex = currentEffects.findIndex((e) => e.effect_type === EFFECT_TYPE);
                const newEffectData = {
                    effect_type: EFFECT_TYPE,
                    params: effectValue,
                };

                if (effectIndex !== -1) {
                    updatedEffects = [...currentEffects];
                    updatedEffects[effectIndex] = {
                        ...updatedEffects[effectIndex],
                        ...newEffectData,
                    };
                } else {
                    updatedEffects = [...currentEffects, newEffectData];
                }
            } else {
                // 清除特效（当用户清除选择时）
                updatedEffects = currentEffects.filter((e) => e.effect_type !== EFFECT_TYPE);
            }

            // 根据是否为贴纸调用不同的action
            if (isSticker) {
                dispatch(
                    updateStickerProperties({
                        id: videoId,
                        updates: { effect: updatedEffects },
                    })
                );
            } else {
                dispatch(
                    updateVideoProperties({
                        id: videoId,
                        updates: { effect: updatedEffects },
                    })
                );
            }
        },
        [videoId, mediaEffects, dispatch, isSticker]
    );

    if (!videoId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何视频片段
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            {/* **改动1: 主容器样式与之前表单对齐** */}
            <div
                className="config-video-effect-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前特效
                </Title>
                {/* **改动2: 优化当前特效显示** */}
                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '16px',
                        border: '1px solid #555555',
                    }}
                >
                    <Text style={{ color: '#FFFFFF' }}>{currentEffect ? `场景特效: ${currentEffect.params}` : '无特效'}</Text>
                </div>

                {/* **改动3: 简化表单逻辑** */}
                <Form form={form} layout="vertical">
                    <Form.Item label="选择特效" name="effect">
                        <Spin spinning={loading}>
                            <Select
                                placeholder="请选择或清除特效"
                                allowClear
                                showSearch
                                filterOption={(input, option) => (option?.children?.toString() || '').toLowerCase().includes(input.toLowerCase())}
                                onChange={handleEffectChange}
                                style={{ width: '98%' }}
                            >
                                {effectsData.map((effect, index) => (
                                    <Option key={effect.id || effect.name || `effect-${index}`} value={effect.name}>
                                        {effect.display_name}
                                        {effect.is_vip ? ' (VIP)' : ''}
                                    </Option>
                                ))}
                            </Select>
                        </Spin>
                    </Form.Item>
                </Form>
            </div>
        </>
    );
};

export default ConfigVideoEffectForm;
